#! -*- coding: utf-8 -*-
import datetime
import json

from mongoengine import (
    StringField, IntField, Q, BooleanField,
    DateTimeField, Document, ReferenceField,
    PointField
)

from app.constants import MTU_TYPE, CURRENCY_TO_SYMBOL
from app.utils import safe_int


class Poi(Document):
    # 临时数据表
    meta = {
        'collection': 'vacation_poi',
    }

    target_id = IntField()
    name = StringField()
    location = PointField()


class Mtu(Document):
    meta = {
        'collection': 'vacation_mtu',
    }

    target_type = IntField()  # 1: poi; 2: product; 3: hotel
    target_id = StringField()
    destination = ReferenceField('Destination')
    category_id = IntField()
    published = BooleanField()
    poi_name = StringField()
    location = PointField()

    def __repr__(self):
        _type = MTU_TYPE.inv_dict().get(self.target_id, "")
        return '<Mtu: %s>' % _type

    def _get_product_info(self, product):
        product_id = product.id
        name = product.name
        name_en = product.name_en
        description = product.description
        x, y = 0, 0
        if product.location:
            x, y = product.location['coordinates']
        address = product.address
        fee = safe_int(product.fee)
        currency = product.currency
        currency = CURRENCY_TO_SYMBOL.get(currency)
        recommended_reason = product.description
        opening_time = product.open_time
        arrival_type = product.arrival_type
        cover = product.cover
        small_covers = json.loads(product.photos) if product.photos else []

        outline = product.outline
        images = []
        outline = json.loads(outline) if outline else {}
        images.append({
            'description': outline.get('text'),
            'images': [outline['image']],
        })

        # if len(small_covers) < 5:
        #     poi = get_object_or_None(Poi, pk=product.poi_id)
        #     try:
        #         poi_ids = json.loads(product.link_pois)
        #         link_poi = Poi.objects.filter(pk__in=poi_ids)[0]
        #     except:
        #         link_poi = None
        #     link_poi = link_poi if link_poi else poi
        #     if link_poi:
        #         items = []
        #         obj = query_site_object(TINYSITE_TYPES.POI, link_poi.pk)
        #         if obj:
        #             waypoints = get_favorite_waypoints(
        #                 obj, limit=4 - len(small_covers), offset=0)
        #             waypoints = waypoints['items']
        #             waypoints = get_waypoints_light(waypoints).values()
        #
        #             # compress result
        #             items.extend([compressed_dict(wp, ('photo_s'))
        #                           for wp in waypoints])
        #             for item in items:
        #                 small_covers.append(item['photo_s'])

        time_consuming_min = product.time_consuming_min
        time_consuming_max = product.time_consuming_max
        website = ''
        tel = ''

        info = {}
        info.update({
            'product_id': str(product_id),
            # 'poi_id': poi_id,
            'name': name,
            'name_en': name_en,
            'tel': tel,
            'mtu_type': self.target_type,
            'description': description,
            'location': {'lng': x, 'lat': y},
            'address': address,
            'fee': fee,
            'currency': currency,
            'recommended_reason': recommended_reason,
            'opening_time': opening_time,
            'arrival_type': arrival_type,
            'cover': cover,
            'small_covers': small_covers,
            'website': website,
            'category_id': str(self.category_id),
            # 'is_booking': self.is_booking,
            # 'stars': self.stars,
            'destination_id': str(self.destination.id),
            # 'prefered': self.prefered,
            'time_consuming_max': time_consuming_max,
            'time_consuming_min': time_consuming_min,
            'travel_time': True if product.product_display_info.travel_time else False,
            'mtu_id': str(self.pk),
            'images': images,
            # 'region': self.region,
            # 'is_set_hotel': product.template_id in [2, 3, 4]  # 酒店接送服务、接送机
            'is_set_hotel': (product.classify and product.classify.name_en in ['pick_up']) or False  # 酒店接送服务、接送机
        })
        return info

    def get_info(self, with_small_covers=False):
        info = {}
        if self.target_type == MTU_TYPE.PRODUCT:
            info = self._get_product_info(self.target_id)

        info.update(mtu_id=str(self.id), distance=0)
        return info

    def get_dialog_count(self):
        condition = Q(mtu=self.id, is_active=True)
        dialogs_count = MtuDialog.objects.filter(condition).count()
        return dialogs_count


class MtuDialog(Document):
    meta = {
        'collection': 'vacation_mtudialog',
    }

    mtu = ReferenceField('Mtu')
    user_id = IntField()
    text = StringField()
    is_active = BooleanField()
    last_modified = DateTimeField(default=datetime.datetime.utcnow)
    date_added = DateTimeField(default=datetime.datetime.utcnow)


class MtuComment(Document):
    meta = {
        'collection': 'vacation_mtucomment',
    }

    mtu = ReferenceField('Mtu')
    user_id = IntField()
    text = StringField()
    is_active = BooleanField()
    liked_count = IntField()
    score = IntField()
    last_modified = DateTimeField(default=datetime.datetime.utcnow)
    date_added = DateTimeField(default=datetime.datetime.utcnow)
